﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;

namespace NotificationLib
{
    public class NotificationQueue
    {
        Queue<Notification> Notifications;        
        public bool Working { get; set; }
        Timer WorkerTimer;

        double WorkerDelay = 8 * 1000; // seconds to ms

        public NotificationQueue()
        {
            Notifications = new Queue<Notification>();
            Working = false;
        }

        public void Add(Notification n)
        {
            lock (Notifications)
            {
                Notifications.Enqueue(n);
            }
            n.Enqueued = DateTime.Now;
        }

      

        public void Start()
        {
            Working = true;
            InitializeTimer();
            StartTimer();
        }

        public void Stop()
        {
            Working = false;
            StopTimer();            
        }

        void StopTimer()
        {
            if (WorkerTimer != null)
            {
                WorkerTimer.Stop();
            }
        }
        void InitializeTimer()
        {
            if (WorkerTimer == null)
            {
                WorkerTimer = new Timer(WorkerDelay);
                WorkerTimer.Elapsed += new ElapsedEventHandler(SendWorker);
                WorkerTimer.AutoReset = false;
            }
        }

        void StartTimer()
        {           
            WorkerTimer.Start();
        }

        void SendNotification(Notification n)
        {
            if (n.Send())
            {
                //sucessfully sent                
            }
            else
            {
                //send failed
                n.LastSendAttempt = DateTime.Now;
                lock (Notifications)
                {
                    Notifications.Enqueue(n);
                }
            }
        }

        void SendWorker(object o, ElapsedEventArgs e)
        {
            if (Working)
            {
                Notification n;
                bool go;
                lock (Notifications)
                {
                    go = Notifications.Count > 0;
                }
                if (go)
                {
                    lock (Notifications)
                    {
                        n = Notifications.Dequeue();
                    }

                    SendNotification(n);
                    
                }
                StartTimer();
            }
        }



    }
}
